package cn.jtfadmin.core.modules.sys.service.impl;

import cn.jtfadmin.base.lang.common.domain.entity.BuildInEntityDelValidUtils;
import cn.jtfadmin.base.lang.common.service.BaseTreeService;
import cn.jtfadmin.base.lang.common.utils.AkUtils;
import cn.jtfadmin.base.lang.enums.BooleanEnum;
import cn.jtfadmin.base.shiro.support.ShiroPasswordMatch;
import cn.jtfadmin.core.constant.OrgTypeConstant;
import cn.jtfadmin.core.enums.UserStatusEnum;
import cn.jtfadmin.core.modules.sys.domain.dto.SysInitPDTO;
import cn.jtfadmin.core.modules.sys.domain.dto.SysPermissionAddPDTO;
import cn.jtfadmin.core.modules.sys.domain.entity.SysDepartEntity;
import cn.jtfadmin.core.modules.sys.domain.entity.SysPermissionEntity;
import cn.jtfadmin.core.modules.sys.domain.entity.SysRoleEntity;
import cn.jtfadmin.core.modules.sys.domain.entity.SysUserEntity;
import cn.jtfadmin.core.modules.sys.service.SysInitService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.jpa.repository.support.JpaRepositoryImplementation;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.CollectionUtils;

import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
import java.util.Objects;


/**
 * 系统初始化服务实现类
 */
@Service
public class SysInitServiceImpl implements SysInitService {


    @Autowired
    protected JpaRepositoryImplementation<SysUserEntity, String> sysUserRepository;

    @Autowired
    protected JpaRepositoryImplementation<SysRoleEntity, String>  sysRoleRepository;

    @Autowired
    protected JpaRepositoryImplementation<SysDepartEntity, String> sysDepartRepository;

    @Autowired
    protected JpaRepositoryImplementation<SysPermissionEntity, String> sysPermissionRepository;

//    protected ShiroPasswordMatch passwordMatch;

    @Autowired
    protected BaseTreeService<SysPermissionEntity> sysPermissionService;


    private String defaultInitDepartmentName = "总公司";


    @Override
    @Transactional
    public void sysInit(SysInitPDTO sysInitPDTO) {
        // 允许删除
        BuildInEntityDelValidUtils.allowDel();
        // 清理所有数据
        cleanAllData();
        sysPermissionRepository.flush();
        // 开始初始化
        doInit(sysInitPDTO);

        // 设置不允许删除
        BuildInEntityDelValidUtils.forbidDel();
    }

    private void doInit(SysInitPDTO sysInitPDTO) {
        List<SysInitPDTO.PermissionInitPDTO> routeMap = sysInitPDTO.getRouteMap();
        List<SysPermissionEntity> list = new ArrayList<>();
        for (int i = 0; i < routeMap.size(); i++) {
            initSaveSysPerm(routeMap.get(i), null, list, i);
        }

        SysDepartEntity com = new SysDepartEntity();
        com.setNo("00001");
        com.setName(defaultInitDepartmentName);
        com.setOrgType(OrgTypeConstant.ORG_TYPE_COMPANY);
        com.setSort(0);
        com = sysDepartRepository.save(com);


        SysRoleEntity roleEntity = new SysRoleEntity();
        roleEntity.setSysDepart(com);
        roleEntity.setPermissionList(list);
        roleEntity.setCode("administrator");
        roleEntity.setDescription("超级管理员");
        roleEntity.setName("超级管理员");
        roleEntity.setAdminFlag(BooleanEnum.TRUE);
        roleEntity = sysRoleRepository.save(roleEntity);

        SysUserEntity userEntity = new SysUserEntity();
        userEntity.setSysDepart(com);
        userEntity.setUsername(sysInitPDTO.getUsername());
        userEntity.setPassword(ShiroPasswordMatch.encode(sysInitPDTO.getPassword()));
        userEntity.setRealname("超级管理员");
        userEntity.setBuildInFlag(BooleanEnum.TRUE);
        userEntity.setStatus(UserStatusEnum.NORMAL);
        userEntity.setRoleList(Arrays.asList(roleEntity));

        sysUserRepository.save(userEntity);
    }

    private void cleanAllData() {
        sysRoleRepository.deleteAll(sysRoleRepository.findAll());
        sysUserRepository.deleteAll(sysUserRepository.findAll());
        sysDepartRepository.deleteAll(
                sysDepartRepository.findAll()
        );
        // 级联删除
        sysPermissionRepository.deleteAll(
                sysPermissionRepository.findAll()
        );

    }

    private void initSaveSysPerm(SysInitPDTO.PermissionInitPDTO permissionInitPDTO, SysPermissionEntity parent, List<SysPermissionEntity> store, Integer sort) {
        SysPermissionAddPDTO sysPermissionAddPDTO = new SysPermissionAddPDTO();
        AkUtils.copyProperties(permissionInitPDTO, sysPermissionAddPDTO);
        if (Objects.nonNull(parent)) {
            sysPermissionAddPDTO.setParentId(parent.getId());
        }
        sysPermissionAddPDTO.setSortNo(sort);
        SysPermissionEntity sysPermissionEntity = sysPermissionService.add(sysPermissionAddPDTO);
        store.add(sysPermissionEntity);
        List<SysInitPDTO.PermissionInitPDTO> children = permissionInitPDTO.getChildren();
        if (!CollectionUtils.isEmpty(children)) {
            for (int i = 0; i < children.size(); i++) {
                initSaveSysPerm(children.get(i), sysPermissionEntity, store, i);
            }
        }
    }
}
